<?

require_once('./lib/authentication.lib.php');
require_once('./lib/sort.lib.php');
require_once('./lib/navigation.lib.php');
require_once('./lib/game.lib.php');

function inc_month($date) {
  $y = substr($date, 0, 4);
  $m = substr($date, 4, 2);
  if ($m == 12) {
    $y++;
    $m = '01';
  } else {
    $m++;
    if ($m < 10) $m = "0" . $m;
  }
  return "$y$m" . "01";
}

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>GOLaberto.com.br</title>
<SCRIPT TYPE="text/javascript" SRC="js/game.js"></SCRIPT>
<SCRIPT TYPE="text/javascript" SRC="js/game_squad.js"></SCRIPT>
<SCRIPT TYPE="text/javascript" SRC="js/game_info.js"></SCRIPT>
<link rel="stylesheet" href="css/style.css" type="text/css">
<link rel="stylesheet" href="css/squad.css" type="text/css">
</head>
<body>

<?
$championship = mysql_escape_string($_GET["id"]);
$phase = mysql_escape_string($_GET["phase"]);

if (isset($_GET["date"]))
{
	$start_date = mysql_escape_string($_GET["date"]);
}
else
{
	$start_date = date("Ym01");
}
?>

<? echo foot_header($championship, "games"); ?>

<?
$query = "SELECT * FROM Championship WHERE id = '$championship';";
$result_champ = mysql_query($query);

$num = mysql_numrows($result_champ);

if ($num == 0)
{
	echo "<H1>Couldn't find championship $championship</H1>";
	exit;
}
$id = mysql_result($result_champ, 0, "id");
$name = mysql_result($result_champ, 0, "name");
$begin = mysql_result($result_champ, 0, "begin");
$end = mysql_result($result_champ, 0, "end");
$point_win = mysql_result($result_champ, 0, "point_win");
$point_draw = mysql_result($result_champ, 0, "point_draw");
$point_loss = mysql_result($result_champ, 0, "point_loss");

if (!$phase)
{
	$query = "SELECT id FROM Phase where championship = '$id' ORDER BY `order` DESC LIMIT 1;";
	$result_phase = mysql_query($query);
	$num_phase = mysql_numrows($result_phase);
	if ($num_phase == 0)
	{
		echo "<H1>Couldn't find any phase</H1>";
		exit;
	}
	$phase = mysql_result($result_phase, 0, "id");
}

$query = "SELECT * FROM Phase where championship = '$id' AND id = '$phase';";
$result_phase = mysql_query($query);
$num_phase = mysql_numrows($result_phase);
if ($num_phase == 0)
{
	echo "<H1>Couldn't find phase $phase</H1>";
	exit;
}

$begin = str_replace("-", "", $begin);
$end = str_replace("-", "", $end);

$begin_str = substr($begin, 0, 4);
$end_str = substr($end, 0, 4);

echo "<div id='conteudo'>\n";
echo "<div class='games'>\n";
echo "<h1>$name $begin_str" . (($begin_str != $end_str) ? "/$end_str" : "") . "</h1>\n";

$query = "SELECT date FROM Game where phase = '$phase' ORDER BY date LIMIT 1;";
$result_start = mysql_query($query);
$num_start = mysql_numrows($result_start);
if ($num_start == 0)
{
	$first_game = $begin;
}
else
{
	$first_game = mysql_result($result_start, 0, "date");
	$first_game = substr($first_game, 0, 10);
	$first_game = str_replace("-", "", $first_game);
}

$query = "SELECT date FROM Game where phase = '$phase' ORDER BY date DESC LIMIT 1;";
$result_start = mysql_query($query);
$num_start = mysql_numrows($result_start);
if ($num_start == 0)
{
	$last_game = $begin;
}
else
{
	$last_game = mysql_result($result_start, 0, "date");
	$last_game = substr($last_game, 0, 10);
	$last_game = str_replace("-", "", $last_game);
}

if ($first_game > $start_date) $start_date = substr($first_game, 0, 6) . "01";
if ($last_game < $start_date) $start_date = substr($last_game, 0, 6) . "01";
$end_date = substr($start_date, 0, 6) . "31";

echo "<select onChange='window.location = \"games.php?id=$championship&phase=$phase&date=\" + this.value'>\n";
$curr_month = substr($first_game, 0, 6) . "01";
$end_month = inc_month(substr($last_game, 0, 6) . "01");
while ($curr_month != $end_month) {
  echo "<option value='$curr_month'";
  if ($curr_month == $start_date) echo " selected";
  echo ">";
  echo date("F", strtotime($curr_month));
  echo "</option>";
  $curr_month = inc_month($curr_month);
}
echo "</select>\n";

$query = "SELECT * FROM Phase where `championship` = $id ORDER BY `order`;";
$result_phase = mysql_query($query);
$num_phase = mysql_numrows($result_phase);

echo "<table class='tab_header'><tr>\n";
for ($i = 0; $i < $num_phase; $i++)
{
	$name_phase = mysql_result($result_phase, $i, "name");
	$id_phase = mysql_result($result_phase, $i, "id");

	if ($id_phase == $phase)
		echo "<td>$name_phase</td>\n";
	else
		echo "<td style='background-color: #999'><a href='games.php?id=$id&phase=$id_phase'>$name_phase</a></td>\n";
}
echo "</tr></table>\n";

# Check the goals
$query = "SELECT game, team, own_goal FROM Goal, Game WHERE Game.id = Goal.game AND phase = '$phase';";
$result_goal = mysql_query($query);
while ($row = mysql_fetch_assoc($result_goal))
{
	if ($row["own_goal"])
		$goals[$row["game"]][$row["team"]]["own"]++;
	else
		$goals[$row["game"]][$row["team"]]["for"]++;
}

# Check the squads
$query = "SELECT game, team, COUNT(1) c FROM player_game GROUP BY game, team;";
$result_squad = mysql_query($query);
while ($row = mysql_fetch_assoc($result_squad))
{
	$squads[$row["game"]][$row["team"]] = $row["c"];
}

echo "<table>\n";

$query = "SELECT Game.id game_id, Game.home, Game.away, Game.phase, Game.home_score, Game.away_score, Game.home_pen, Game.away_pen, Game.attendance, Game.date, Game.round, Game.played, Game.referee, Game.stadium, Home.name home_name, Home.logo home_logo, Away.name away_name, Away.logo away_logo FROM Game LEFT JOIN Team Home ON Game.home = Home.id LEFT JOIN Team Away ON Game.away = Away.id WHERE `phase` = '$phase' ORDER BY Game.played DESC, Game.date ASC, Game.round ASC, Home.name ASC;";

$result_game = mysql_query($query);
$num_game = mysql_numrows($result_game);
$prev_date = "";
$prev_round = "";
$prev_played = "";
$team_table = array();
while ($row = mysql_fetch_assoc($result_game))
{
	$id_game = $row["game_id"];
	$home = $row["home"];
	$away = $row["away"];
	$home_score = $row["home_score"];
	$away_score = $row["away_score"];
	$home_pen = $row["home_pen"];
	$away_pen = $row["away_pen"];
	$attendance = $row["attendance"];
	$date = $row["date"];
	$round = $row["round"];
	$referee = $row["referee"];
	$stadium = $row["stadium"];
	$played = $row["played"];
	$home_name = $row["home_name"];
	$away_name = $row["away_name"];

	if ($played !== "scheduled")
	{
		$team_table[$home]["gf"] += $home_score;
		$team_table[$home]["ga"] += $away_score;
		$team_table[$home]["g"] += 1;
		$team_table[$home]["gp"] += $home_pen;
		$team_table[$away]["gf"] += $away_score;
		$team_table[$away]["ga"] += $home_score;
		$team_table[$away]["g"] += 1;
		$team_table[$away]["gp"] += $away_pen;
		$team_table[$away]["g_away"] += $away_score;
		if ($home_score > $away_score)
		{
			$team_table[$home]["w"] += 1;
			$team_table[$home]["pt"] += $point_win;
			$team_table[$away]["l"] += 1;
		}
		else if ($home_score < $away_score)
		{
			$team_table[$away]["w"] += 1;
			$team_table[$away]["pt"] += $point_win;
			$team_table[$home]["l"] += 1;
		}
		else
		{
			$team_table[$home]["d"] += 1;
			$team_table[$home]["pt"] += $point_draw;
			$team_table[$away]["d"] += 1;
			$team_table[$away]["pt"] += 1;
		}
	}

	if ($date)
	{
		if (substr(str_replace("-", "", $date), 0, 8) < $start_date or
				substr(str_replace("-", "", $date), 0, 8) > $end_date)
		{
			continue;
		}
	}

	if ($played !== $prev_played)
	{
		if ($played === "playing")
			echo "<tr><td colspan='10' class='game_toplay'>Playing</td></tr>\n";
		else if ($played === "played")
			echo "<tr><td colspan='10' class='game_toplay'>Played</td></tr>\n";
		else if ($played === "scheduled")
			echo "<tr><td colspan='10' class='game_toplay'>Scheduled</td></tr>\n";
		$prev_played = $played;
		$prev_round = "";
		$prev_date = "";
	}

	if (isset($round) and $round and $round !== $prev_round)
	{
		echo "<tr><td colspan='10' class='game_round'>Round $round</td></tr>\n";
		$prev_round = $round;
		$prev_date = "";
	}

	if (substr($date, 0, 10) !== substr($prev_date, 0, 10))
	{
		if ($date === '0000-00-00 00:00:00') $date_str = "No date";
		else $date_str = date("d/m/Y - l", strtotime($date));
		echo "<tr><td colspan='10' class='game_date'>$date_str</td></tr>\n";
		$prev_date = $date;
	}

	echo "<tr>\n";
	echo "<td class='game_score'>\n";
	echo write_game_score($row, true);

	echo "<DIV class='game_info' id='game_info_".$row["game_id"]."'>\n";
#	echo write_game_info($row);
	echo "</DIV>\n";
	echo "</td>\n";

	echo "<td valign='top'>";
	if (!$referee) echo "<IMG WIDTH='14' HEIGHT='14' SRC='img/whistle.gif'>";
	echo "</td>\n";

	echo "<td valign='top'>";
	if (!$stadium) echo "<IMG WIDTH='14' HEIGHT='14' SRC='img/stadium.jpg'>";
	echo "</td>\n";

	echo "<td valign='top'>";
	if (!$attendance) echo "<IMG WIDTH='14' HEIGHT='14' SRC='img/people.gif'>";
	echo "</td>\n";

	echo "<td valign='top'>";
	if ($home_score != $goals[$id_game][$home]["for"] + $goals[$id_game][$away]["own"] or $away_score != $goals[$id_game][$away]["for"] + $goals[$id_game][$home]["own"])
	{
		echo "<IMG WIDTH='14' HEIGHT='14' SRC='img/soccer-ball.jpg'>";
	}
	echo "</td>\n";

	echo "<td valign='top'>";
	if ($squads[$id_game][$home] < 11 or $squads[$id_game][$away] < 11)
		echo "<IMG WIDTH='14' HEIGHT='14' SRC='img/shirt.png'>";
	echo "</td>\n";

	echo "<td class='show_info'><span onClick='writeInfo($id_game, this.parentNode.parentNode, this);'>Info</span></td>\n";
	echo "<td class='edit'><a href='javascript:edit_game($championship, $id_game);'>Edit</a></td>\n";
	echo "</tr>\n";
}

echo "</table>\n";
echo "</div>\n";

# Write the current table
echo "<div class='team_table'>\n";
echo "<h3>OUTROS CAMPEONATOS</h3>\n";
echo "<select>\n";
echo "</select>\n";

echo "<h3>CLASSIFICACAO</h3>\n";
$query = "SELECT * FROM `Group` WHERE `phase` = '$phase';";
$result_group = mysql_query($query);
$num_group = mysql_numrows($result_group);
for ($k = 0; $k < $num_group; $k++)
{
	$id_group = mysql_result($result_group, $k, "id");
	$name_group = mysql_result($result_group, $k, "name");
	$promoted = mysql_result($result_group, $k, "promoted");
	$relegated = mysql_result($result_group, $k, "relegated");

	echo "<h3>$name_group</h3>\n";

	$group_teams = array();

	$query = "SELECT Team.id, Team.name, team_group.add_sub FROM Team, team_group WHERE team_group.group = '$id_group' AND Team.id = team_group.team;";
	$result_teams = mysql_query($query);
	$num_teams = mysql_numrows($result_teams);
	for ($l = 0; $l < $num_teams; $l++)
	{
		$team_id = mysql_result($result_teams, $l, "Team.id");
		$team_name = mysql_result($result_teams, $l, "Team.name");
		$add_sub = mysql_result($result_teams, $l, "team_group.add_sub");

		$group_teams[] = $team_id;

		$team_table[$team_id]["name"] = $team_name;
		if (!isset($team_table[$team_id]["g"]))
			$team_table[$team_id]["g"] = 0;
		if (!isset($team_table[$team_id]["pt"]))
			$team_table[$team_id]["pt"] = 0;
		if (!isset($team_table[$team_id]["w"]))
			$team_table[$team_id]["w"] = 0;
		if (!isset($team_table[$team_id]["d"]))
			$team_table[$team_id]["d"] = 0;
		if (!isset($team_table[$team_id]["l"]))
			$team_table[$team_id]["l"] = 0;
		if (!isset($team_table[$team_id]["gf"]))
			$team_table[$team_id]["gf"] = 0;
		if (!isset($team_table[$team_id]["ga"]))
			$team_table[$team_id]["ga"] = 0;
		if (!isset($team_table[$team_id]["gp"]))
			$team_table[$team_id]["gp"] = 0;
		if (!isset($team_table[$team_id]["g_away"]))
			$team_table[$team_id]["g_away"] = 0;

		$team_table[$team_id]["pt"] += $add_sub;

		$team_table[$team_id]["gd"] = $team_table[$team_id]["gf"] - $team_table[$team_id]["ga"];
	}

	$team_table = multi_sort($team_table, array("pt", "w", "gd", "gf", "gp", "g_away", array("name", true)), false);

	echo "<table class='full'>\n";
	echo "<tr class='table_head'>";
	echo "<th width=5%>Pos</th>\n";
	echo "<th width>Name</th>\n";
	echo "<th width=5%>Pts</th>\n";
	echo "<th width=5%>G</th>\n";
	echo "<th width=5%>W</th>\n";
#	echo "<th width=5%>D</th>\n";
#	echo "<th width=5%>L</th>\n";
#	echo "<th width=5%>GF</th>\n";
#	echo "<th width=5%>GA</th>\n";
	echo "<th width=5%>GD</th>\n";
	echo "</tr>\n";
	$count = 0;
	while (list($key, $value) = each($team_table))
	{
		$ret = array_search($key, $group_teams);
		if ($ret !== false)
		{
			if ($count < $promoted)
			{
				$class = "promoted";
			}
			else if (count($team_table) - $count - 1 < $relegated)
			{
				$class = "relegated";
			}
			else
			{
				$class = "table_line";
			}
			echo "<tr class=$class>\n";
			echo "<td align=right>" . ++$count . "</td>\n";
			echo "<td><a href='team.php?champ=$id&team=$key'>" . $value["name"] . "</a></td>\n";
			echo "<td align=center><b>" . $value["pt"] . "</b></td>\n";
			echo "<td align=center>" . $value["g"] . "</td>\n";
			echo "<td align=center>" . $value["w"] . "</td>\n";
#			echo "<td align=center>" . $value["d"] . "</td>\n";
#			echo "<td align=center>" . $value["l"] . "</td>\n";
#			echo "<td align=center>" . $value["gf"] . "</td>\n";
#			echo "<td align=center>" . $value["ga"] . "</td>\n";
			echo "<td align=center>" . $value["gd"] . "</td>\n";
			echo "</tr>\n";
		}
	}
	echo "</table>\n";
}
echo "</div>\n"; # team_table

echo "<div style='clear: both'></div>\n";

echo "</div>\n"; # conteudo

echo foot_footer($championship, "games");


echo "</div>\n";

echo "</div>\n";
?>

<BR>
<BR>

</BODY>
</HTML>
